package com.jml.mooc.ch3;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;

/**
 * @author
 */
public final class Server {

    public static void main(String[] args) throws Exception {
        //代表server中线程
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //代表client的线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            //设置连接的属性
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //给后面指定的客户端的连接，设置一下TCP的基本属性
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //在每次创建客户端连接的时候，可以绑定基本的属性
                    .childAttr(AttributeKey.newInstance("childAttr"), "childAttrValue")
                    //在服务端启动的过程中有一些什么逻辑
                    .handler(new ServerHandler())
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            //对每一条新连接的数据流读写的逻辑
                            //ch.pipeline().addLast(new AuthHandler());
                            //..
                        }
                    });
            //bind方法就是服务端创建Channel的入口，将连接初始化
            ChannelFuture f = b.bind(8888).sync();

            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}